package com.tekj.cxqcb.view.Module.activity.StoreModule;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.services.core.PoiItem;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.entity.LocalMedia;
import com.tekj.cxqcb.R;
import com.tekj.cxqcb.operation.BusinessDao;
import com.tekj.cxqcb.operation.resultBean.PubStatusBean;
import com.tekj.cxqcb.operation.resultBean.UploadFiles;
import com.tekj.cxqcb.view.Module.activity.Address2Activity;
import com.tekj.cxqcb.view.Module.activity.PoiAroundSearchActivity;
import com.tekj.cxqcb.view.Module.adapter.ProposalAdapter;
import com.tekj.cxqcb.view.Module.bean.UpShopInsertBean;
import com.tekj.cxqcb.view.Module.decoration.SpacesItemDecoration;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import common.base.activity.BaseActivity;
import common.base.operationHelper.Bean.BindingViewBean;
import common.tool.Tools;
import es.dmoral.toasty.Toasty;

/**
 * 门店管理(修改&创建)
 */
public class AdministrationActivity extends BaseActivity {

    @BindView(R.id.img_back)
    ImageView imgBack;
    @BindView(R.id.tv_l)
    TextView tvL;
    @BindView(R.id.ll_back)
    LinearLayout llBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.iv_r)
    ImageView ivR;
    @BindView(R.id.tv_r)
    TextView tvR;
    @BindView(R.id.ll_right)
    LinearLayout llRight;
    @BindView(R.id.rl_title_bg)
    RelativeLayout rlTitleBg;
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.tv_adderss)
    TextView tvAdderss;
    @BindView(R.id.tv_detailed_adderss)
    EditText tvDetailedAdderss;
    @BindView(R.id.rv_photo)
    RecyclerView rvPhoto;
    @BindView(R.id.img_business_license)
    ImageView imgBusinessLicense;
    @BindView(R.id.img_sfz_z)
    ImageView imgSfzZ;
    @BindView(R.id.img_sfz_f)
    ImageView imgSfzF;
    @BindView(R.id.img_warrant)
    ImageView imgWarrant;
    @BindView(R.id.tv_adderss2)
    TextView tvAdderss2;
    @BindView(R.id.btn_Apply)
    TextView btnApply;

    private ProposalAdapter adapter;
    private List<LocalMedia> localMedias;
    private LocalMedia businessLicense;
    private LocalMedia SfzZ;
    private LocalMedia SfzF;
    private LocalMedia Warrant;
    private BusinessDao businessDao;

    private String shopPhoto;
    private String businessPhoto;
    private String sfzZPhoto;
    private String sfzFPhoto;
    private String warrantPhoto;

    @Override
    public void init() {
        tvTitle.setText("店铺管理");
        businessDao = new BusinessDao(this, this);
        localMedias = new ArrayList<>();
        adapter = new ProposalAdapter(activity, localMedias, localMedias.size() + 1);

        adapter.setOnCallbackListener(new ProposalAdapter.OnCallbackListener() {
            @Override
            public void onAddPhotoClick() {
                //添加图片
                Tools.InitPictureSelector(activity, false, 101, localMedias, 9);
            }

            @Override
            public void onPicturePreview(int position) {
                //图片预览
                PictureSelector.create(activity).externalPicturePreview(position, localMedias);
            }

            @Override
            public void onPictureDelete(int position) {
                localMedias.remove(position);
                shopPhoto = DeletePhoto(position);
                adapter.setList(localMedias, localMedias.size() + 1);
            }
        });

        rvPhoto.setLayoutManager(new GridLayoutManager(activity, 3));
        rvPhoto.setAdapter(adapter);
        rvPhoto.addItemDecoration(new SpacesItemDecoration(10));
    }

    @Override
    public int setLayout() {
        return R.layout.activity_administration;
    }

    @Override
    public void initLoadStart() {
        showDialog();
    }

    @Override
    public void initLoadEnd() {
        activity.dialog.dismiss();
    }

    @Override
    public void initBindingView(Object mBean) {

        BindingViewBean bindingViewBean = (BindingViewBean) mBean;
        switch (bindingViewBean.getmEnumStatus()) {
            case 多文件上传:
                UploadFiles uploadFiles = (UploadFiles) bindingViewBean.getBean();
                if (uploadFiles.getTypeName().equals("店铺形象")) {
                    shopPhoto = uploadFiles.getData().getUploadFilePath();
//                    Toasty.normal(activity, "成功").show();
                } else if (uploadFiles.getTypeName().equals("营业执照")) {
                    businessPhoto = uploadFiles.getData().getUploadFilePath();
                } else if (uploadFiles.getTypeName().equals("身份证正")) {
                    sfzZPhoto = uploadFiles.getData().getUploadFilePath();
                } else if (uploadFiles.getTypeName().equals("身份证反")) {
                    sfzFPhoto = uploadFiles.getData().getUploadFilePath();
                } else if (uploadFiles.getTypeName().equals("店铺头像")) {
                    warrantPhoto = uploadFiles.getData().getUploadFilePath();
                }

                break;
            case 添加申请店铺:
                PubStatusBean pubStatusBean = (PubStatusBean) bindingViewBean.getBean();
                if (pubStatusBean.getCode().equals("0000000")) {
                    finish();
                } else
                    Toasty.normal(activity, pubStatusBean.getMsg()).show();
                break;
        }

    }

    String region, province, city, regionid;
    PoiItem poiItem;
    double latitude, longitude;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK)
            switch (requestCode) {
                case 101:
                    localMedias = PictureSelector.obtainMultipleResult(data);
                    adapter.setList(localMedias, localMedias.size() + 1);
                    List<File> list = new ArrayList<>();
                    for (int i = 0; i < localMedias.size(); i++) {
                        if (localMedias.get(i) != null && localMedias.get(i).getCompressPath() != null && !localMedias.get(i).getCompressPath().equals("")) {
                            list.add(new File(localMedias.get(i).getCompressPath()));
                        }
                    }
                    businessDao.uploadFiles(list, "店铺形象");
                    break;
                case 102:
                    businessLicense = PictureSelector.obtainMultipleResult(data).get(0);
                    Tools.picasso(businessLicense.getCompressPath(), imgBusinessLicense);
                    List<File> list2 = new ArrayList<>();
                    list2.add(new File(businessLicense.getCompressPath() == null ? businessLicense.getPath() : businessLicense.getCompressPath()));
                    businessDao.uploadFiles(list2, "营业执照");
                    break;
                case 103:
                    SfzZ = PictureSelector.obtainMultipleResult(data).get(0);
                    Tools.picasso(SfzZ.getCompressPath(), imgSfzZ);

                    List<File> list3 = new ArrayList<>();
                    list3.add(new File(SfzZ.getCompressPath() == null ? SfzZ.getPath() : SfzZ.getCompressPath()));
                    businessDao.uploadFiles(list3, "身份证正");

                    break;
                case 104:
                    SfzF = PictureSelector.obtainMultipleResult(data).get(0);
                    Tools.picasso(SfzF.getCompressPath(), imgSfzF);

                    List<File> list4 = new ArrayList<>();
                    list4.add(new File(SfzF.getCompressPath() == null ? SfzF.getPath() : SfzF.getCompressPath()));
                    businessDao.uploadFiles(list4, "身份证反");

                    break;
                case 105:
                    Warrant = PictureSelector.obtainMultipleResult(data).get(0);
                    Tools.picasso(Warrant.getCompressPath(), imgWarrant);

                    List<File> list5 = new ArrayList<>();
                    list5.add(new File(Warrant.getCompressPath() == null ? Warrant.getPath() : Warrant.getCompressPath()));
                    businessDao.uploadFiles(list5, "店铺头像");

                    break;
                case 106:
                    province = data.getStringExtra("province");
                    city = data.getStringExtra("city");
                    region = data.getStringExtra("district");
                    regionid = data.getStringExtra("region");
                    tvAdderss.setText(province + " " + city + " " + region);
                    break;
                case 107:
                    poiItem = (PoiItem) data.getParcelableExtra("poidata");
                    latitude = poiItem.getLatLonPoint().getLatitude();
                    longitude = poiItem.getLatLonPoint().getLongitude();
                    tvAdderss2.setText(poiItem.getSnippet());
                    break;
            }
    }


    @OnClick({R.id.ll_back, R.id.tv_adderss, R.id.tv_adderss2, R.id.img_business_license,
            R.id.img_sfz_z, R.id.img_sfz_f, R.id.img_warrant,
            R.id.btn_Apply})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_back:
                finish();
                break;
            case R.id.btn_Apply:
                UpData();
//                finish();
                break;
            case R.id.tv_adderss:
                startActivityForResult(new Intent(activity, Address2Activity.class), 106);
                break;
            case R.id.tv_adderss2:
                startActivityForResult(new Intent(activity, PoiAroundSearchActivity.class), 107);
                break;
            case R.id.img_business_license:
                Tools.InitPictureSelector(activity, false, 102, null, 1);
                break;
            case R.id.img_sfz_z:
                Tools.InitPictureSelector(activity, false, 103, null, 1);
                break;
            case R.id.img_sfz_f:
                Tools.InitPictureSelector(activity, false, 104, null, 1);
                break;
            case R.id.img_warrant:
                Tools.InitPictureSelector(activity, false, 105, null, 1);
                break;

        }
    }

    /**
     * 店铺信息上传
     */
    void UpData() {

        UpShopInsertBean bean = new UpShopInsertBean();
        if (etName.getText().toString().equals("")) {
            Toasty.normal(activity, "请填写店铺名称").show();
            return;
        }
        bean.setShopName(etName.getText().toString());


        if (etPhone.getText().toString().equals("")) {
            Toasty.normal(activity, "请填写店铺电话").show();
            return;
        }
        bean.setShopTel(etPhone.getText().toString());

        if (regionid.equals("")) {
            Toasty.normal(activity, "请选择店铺所在省/市/区").show();
            return;
        }
//        bean.setProvince(province);
//        bean.setCity(city);
        bean.setRegion(regionid);

        if (tvAdderss2.getText().toString().equals("")) {
            Toasty.normal(activity, "请选择店铺详细地址").show();
            return;
        }
        bean.setAddress(tvDetailedAdderss.getText().toString());
        bean.setLatitude(latitude + "");
        bean.setLongitude(longitude + "");

        if (localMedias.size() == 0 || shopPhoto == null) {
            Toasty.normal(activity, "未选择店铺形象图或图片上传未成功，请重新选择").show();
            return;
        }
        bean.setShopImage(shopPhoto);

        if (businessLicense == null || businessPhoto == null) {
            Toasty.normal(activity, "未选择营业执照或图片上传未成功，请重新选择").show();
            return;
        }
        bean.setBusinessLicense(businessPhoto);

        if (sfzFPhoto == null || sfzZPhoto == null) {
            Toasty.normal(activity, "未选择身份证或图片上传未成功，请重新选择").show();
            return;
        }
        bean.setIdcardOne(sfzZPhoto);
        bean.setIdcardTwo(sfzFPhoto);

        if (warrantPhoto == null) {
            Toasty.normal(activity, "未选择店铺头像或图片上传未成功，请重新选择").show();
            return;
        }
        bean.setAuthorization(warrantPhoto);

        businessDao.ApiShopInsert(bean);

    }


    String DeletePhoto(int p) {
        if (shopPhoto == null || shopPhoto.equals("")) {
            return "";
        }
        String[] photos = shopPhoto.split(",");

        photos[p] = "";

        String returns = "";
        for (int i = 0; i < photos.length; i++) {
            if (!photos.equals("")) {
                returns = i == 0 ? photos[i] : "," + photos[i];
            }
        }
        return returns;
    }

}
